<?php

namespace app\checkin\controller;

use app\checkin\model\PointsRecord as PointsModel;
use app\checkin\model\Member as MemberModel;
use think\admin\helper\QueryHelper;

/**
 * 积分明细管理
 * @class Points
 * @package app\checkin\controller
 */
class Points extends Base
{
    /**
     * 积分明细列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '积分明细';
        PointsModel::mQuery()->layTable(function () {
            $this->assign('stores', $this->getAccessibleStores());
        }, function (QueryHelper $query) {
            $query->equal('type,source,status,store_id')->dateBetween('create_time');
            $keyword = trim($this->request->get('keyword', ''));
            if ($keyword !== '') {
                $query->where(function ($q) use ($keyword) {
                    $q->whereRaw('member_id IN (SELECT id FROM ' . MemberModel::mk()->getTable() . ' WHERE name LIKE :kw OR phone LIKE :kw)', ['kw' => "%{$keyword}%"]);
                });
            }
            // 数据权限：非总账号显示本店记录 + 与本店有关系会员的所有跨店记录
            if (!$this->isMaster) {
                $relTable = \app\checkin\model\MemberStore::mk()->getTable();
                $sid = $this->storeId;
                $query->where(function ($q) use ($relTable, $sid) {
                    $q->where(['store_id' => $sid])
                      ->whereOrRaw("member_id IN (SELECT member_id FROM {$relTable} WHERE store_id = :sid)", ['sid' => $sid]);
                });
            }
            $query->with([
                'member' => static function ($q) { $q->field('id,name,phone'); },
                'store'  => static function ($q) { $q->field('id,name'); },
                'operator' => static function ($q) { $q->field('id,username'); },
            ]);
        });
    }
}
